package com.ace3l.legal.backend.dao;

import com.ace3l.legal.backend.domain.User;
import com.synesthesiaconsulting.utils.PasswordUtilities;


import javax.persistence.*;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ageer
 * Date: Jul 22, 2008
 * Time: 7:12:49 AM
 * To change this template use File | Settings | File Templates.
 */
@Transactional
public class UserDao {
    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public User saveUser(User myUser) {
        byte[] salt = PasswordUtilities.getSalt();
        byte[] hash = PasswordUtilities.applySalt(myUser.getPassword(), salt);
        myUser.setHash(hash);
        myUser.setSalt(salt);

        entityManager.persist(myUser);
        return myUser;
    }

     public void deleteUser(User myUser) {
        entityManager.remove(myUser);
    }

    public User getUser(String username) {
        Query q = entityManager.createNamedQuery("user.byusername");
        q.setParameter(1, username);
        User myUser = null;
        try {
            myUser = (User)q.getSingleResult();
        } catch (Exception e) { }
        return myUser;
    }

   
    public boolean authenticateUser(String username, String password) {
        User myUser = getUser(username);
        if (myUser == null) return false;
        byte[] salt = myUser.getSalt();
        byte[] tryHash = PasswordUtilities.applySalt(password, salt);
        byte[] storedHash = myUser.getHash();

        boolean authenticated = true;
        for (int i = 0; i < tryHash.length; i++) {
            authenticated = (authenticated && (tryHash[i]==storedHash[i]));
        }
        return authenticated;
    }
}
